//
//  UZCommonMethod.m
//  WMYRiceNoodles
//
//  Created by mac on 13-12-18.
//  Copyright (c) 2013年 mac. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "UZCommonMethod.h"

@implementation UZCommonMethod : NSObject

//+ (void)callPhone:(NSString *)phoneNum superView:(UIView *)view
//{
//    UIWebView *webview = [[UIWebView alloc] initWithFrame:CGRectZero];
//    NSURL *url = [NSURL URLWithString:[@"tel://" stringByAppendingString:phoneNumber]];
//    [webview loadRequest:[NSURLRequest requestWithURL:url]];
//    [view addSubview:webview];
//}

+ (void)settingButton:(UIButton *)button
                Image:(NSString *)imageUrl
      hightLightImage:(NSString *)highLightImageUrl
         disableImage:(NSString *)disableImageUrl
{
    [button setImage:[UIImage imageNamed:imageUrl]
            forState:UIControlStateNormal];
    
    [button setImage:[UIImage imageNamed:highLightImageUrl]
            forState:UIControlStateHighlighted];
    
    [button setImage:[UIImage imageNamed:disableImageUrl]
            forState:UIControlStateDisabled];
}


+ (void)settingButton:(UIButton *)button
                Image:(NSString *)imageUrl
      hightLightImage:(NSString *)highLightImageUrl
{
    [button setImage:[UIImage imageNamed:imageUrl]
            forState:UIControlStateNormal];
    
    [button setImage:[UIImage imageNamed:highLightImageUrl]
            forState:UIControlStateHighlighted];
}


+ (void)settingButton:(UIButton *)button
                Image:(NSString *)imageUrl
        selectedImage:(NSString *)selectedImageUrl
{
    [button setImage:[UIImage imageNamed:imageUrl]
            forState:UIControlStateNormal];
    
    [button setImage:[UIImage imageNamed:selectedImageUrl]
            forState:UIControlStateSelected];
}


+ (void)hiddleExtendCellFromTableview:(UITableView *)tableview
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
    view.backgroundColor = [UIColor clearColor];
    [tableview setTableFooterView:view];
}


//+ (void)settingBackButtonImage:(NSString *)imagename andSelectedImage:(NSString *)selImagename
//{
//    UIImage* backImage = [[UIImage imageNamed:imagename]
//                          resizableImageWithCapInsets:UIEdgeInsetsMake(0, 20, 0, 0)];
//    UIImage* backImageSel = [[UIImage imageNamed:selImagename]
//                             resizableImageWithCapInsets:UIEdgeInsetsMake(0, 20, 0, 0)];
//    
//    if (IOS7) {
//        [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
//        [[UINavigationBar appearance] setBackIndicatorImage:backImage];
//        [[UINavigationBar appearance] setBackIndicatorTransitionMaskImage:backImageSel];
//    }
//    else{
//        [[UIBarButtonItem appearance] setBackButtonBackgroundImage:backImage
//                                                          forState:UIControlStateNormal
//                                                        barMetrics:UIBarMetricsDefault];
//        [[UIBarButtonItem appearance] setBackButtonBackgroundImage:backImageSel
//                                                          forState:UIControlStateHighlighted
//                                                        barMetrics:UIBarMetricsDefault];
//    }
//    
//    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(-1000, -1000)
//                                                         forBarMetrics:UIBarMetricsDefault];
//    
//    
//}


//+ (void)settingLeftButtonImage:(NSString *)imagename
//                 selectedImage:(NSString *)selectedImagename
//                        action:(SEL)action
//               andAtButtonItem:(UIBarButtonItem *)buttonItem
//{
//    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//    [button setBackgroundImage:[UIImage imageNamed:imagename]
//                      forState:UIControlStateNormal];
//    [button setBackgroundImage:[UIImage imageNamed:selectedImagename]
//                      forState:UIControlStateHighlighted];
//    [button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
//
//    UIBarButtonItem *mybuttonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
//#warning 内存溢出
//    buttonItem = mybuttonItem;
//}


+ (void)settingBackButtonImage:(NSString *)imagename
                 selectedImage:(NSString *)selectedImagename
                  andContrller:(UIViewController *)controller
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:@"返回" forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:imagename]
            forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:selectedImagename]
            forState:UIControlStateHighlighted];
    [button addTarget:self action:@selector(backToFather:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *mybuttonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    
    controller.navigationItem.leftBarButtonItem = mybuttonItem;
}
+ (void)backToFather:(UIButton *)sender
{
    UINavigationBar *navigationBar = (UINavigationBar *)sender.superview;
    UINavigationController *nc = (UINavigationController *)[self GetViewController:navigationBar];
    [nc popViewControllerAnimated:YES];
}
+ (UIViewController*)GetViewController:(UIView*)uView
{
    for (UIView* next = [uView superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController*)nextResponder;
        }
    }
    return nil;
}


+ (CGFloat)checkSystemVersion
{
    static dispatch_once_t onceToken;
    __block float systemVersion = 0;
    dispatch_once(&onceToken, ^{
        systemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
    });
    return systemVersion;
}

+ (NSString *)checkAPPVersion
{
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    
    NSString *appVersion = [infoDic objectForKey:@"CFBundleVersion"];
    
    return appVersion;
}

+(NSDictionary* )getUserInfoDict{
    
    NSUserDefaults *loginDefault = [NSUserDefaults standardUserDefaults];
    
    //获取历史登录账号
    NSDictionary *UserInfoDic=@{
                                @"code":[self fuckNULL:[loginDefault objectForKey:@"code"]],
                                @"message":[self fuckNULL:[loginDefault objectForKey:@"message"]],
                                @"sessionKey":[self fuckNULL:[loginDefault objectForKey:@"sessionKey"]],
                                @"u_id":[self fuckNULL:[loginDefault objectForKey:@"u_id"]]
                                };
    
    return UserInfoDic;
}

+ (NSString*)fuckNULL:(NSObject*)obj
{
    if (obj == nil || [obj isKindOfClass:[NSNull class]]){
        return @"";
    }else if ([obj isKindOfClass:[NSNumber class]]) {
        return [NSString stringWithFormat:@"%@",obj];
    }else{
        return [NSString stringWithFormat:@"%@",obj];
    }
}


+(int)findStrIndex:(NSString *)findStr fromString:(NSString *)sourceStr
{
    NSRange range = [sourceStr rangeOfString:findStr];
    
    return (int)range.location;
}


+ (NSString *)getTimeNow
{
    NSString* date;
    
    NSDateFormatter * formatter = [[NSDateFormatter alloc ] init];
    [formatter setDateFormat:@"YYYY-MM-dd"];
    date = [formatter stringFromDate:[NSDate date]];
    NSString *timeNow = [[NSString alloc] initWithFormat:@"%@", date];
    
    return timeNow;
}


+ (NSString *)getTimeFromTimeInterval:(double)timeInterval
{
    
    NSString* date;
    
    NSDateFormatter * formatter = [[NSDateFormatter alloc ] init];
    
    [formatter setDateFormat:@"YYYY-MM-dd"];
    
    date = [formatter stringFromDate:[NSDate dateWithTimeIntervalSinceNow:timeInterval] ];
    
    NSString *timeAfter = [[NSString alloc] initWithFormat:@"%@", date];
    
    return timeAfter;
    
}

#pragma mark - 类方法 (设置颜色)
//  设置颜色
+ (UIColor *)setColorWithRed:(CGFloat)red
                       Green:(CGFloat)green
                        Blue:(CGFloat)blue
                       Alpha:(CGFloat)alpha
{
    CGFloat color = 255;
    
    CGFloat _red = red / color;
    CGFloat _green = green / color;
    CGFloat _blue = blue / color;
    CGFloat _alpha = alpha;
    
    return  [UIColor colorWithRed:_red green:_green blue:_blue alpha:_alpha];
}

//  在 view 的指定位置加指定颜色的线
+ (UIView *) initLineInView:(UIView *)aView
                  withColor:(UIColor *)color
                   AndFrame:(CGRect)frame
{
    UIView * line = [[UIView alloc] init];
    line.backgroundColor = color;
    line.frame = frame;
    [aView addSubview:line];
    return line;
}


#pragma mark 匹配账户合法性(3_16位_字母数字和下划线的组合)

//验证用户输入不能为空
+(BOOL)checkUserInput:(NSString *)str
{
    if ([str length] == 0)
    {
        return NO;
    }
    
    NSInteger length = [str stringByReplacingOccurrencesOfString:@" " withString:@""].length;
    
    if (length==0)
    {
        return NO;
    }
    
    return YES;
}

//验证用户名
+(BOOL)checkUserNameIsRight:(NSString *)str
{
    if ([str length] == 0)
    {
        return NO;
    }
    
    NSString *regex = @"^[a-zA-Z][a-zA-Z0-9_]{3,16}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:str];
    
    if (!isMatch)
    {
        return NO;
    }
    
    return YES;
}


//验证密码
+(BOOL)checkPassWordIsRight:(NSString *)str
{
    if ([str length] == 0)
    {
        return NO;
    }
    
    NSString *regex = @"^[a-zA-Z0-9_]{6,20}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:str];
    
    if (!isMatch)
    {
        return NO;
    }
    
    return YES;
}


//验证手机格式
+ (BOOL)checkTel:(NSString *)str
{
    if ([str length] == 0)
    {
        return NO;
    }
    
    NSString *regex = @"^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\\d{8}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:str];
    
    if (!isMatch)
    {
        return NO;
    }
    
    return YES;
}

//验证邮箱
+(BOOL)checkEmailWithRegex:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

/**
 *  显示标识
 *
 *  @param status 状态码
 */
//+(void)showErrorMessageByStautus:(NSString *)status
//{
//    NSInteger code = [status integerValue];
//    
//    switch (code)
//    {
//        case 200:
//            [SVProgressHUD showSuccessWithStatus:@"成功"];
//            break;
//        case 301:
//            [SVProgressHUD showErrorWithStatus:@"手机号或一卡通号输入不正确或不是业主"];
//            break;
//        case 302:
//            [SVProgressHUD showErrorWithStatus:@"手机号或一卡通已注册，不能再次注册"];
//            break;
//        case 303:
//            [SVProgressHUD showErrorWithStatus:@"验证码错误"];
//            break;
//        case 304:
//            [SVProgressHUD showErrorWithStatus:@"登陆已失效，建议重新登陆"];
//            break;
//        case 305:
//            [SVProgressHUD showErrorWithStatus:@"验证码已过期"];
//            break;
//        case 306:
//            [SVProgressHUD showErrorWithStatus:@"要绑定的手机号码在业主信息中不存在"];
//            break;
//        case 307:
//            [SVProgressHUD showErrorWithStatus:@"用户名或密码错误"];
//            break;
//        case 308:
//            [SVProgressHUD showErrorWithStatus:@"密码错误"];
//            break;
//        case 309:
//            [SVProgressHUD showErrorWithStatus:@"解除绑定失败，没有绑定业主"];
//            break;
//        case 310:
//            [SVProgressHUD showErrorWithStatus:@"权限不足"];
//            break;
//        case 311:
//            [SVProgressHUD showErrorWithStatus:@"业主没有登记手机号"];
//            break;
//        case 312:
//            [SVProgressHUD showErrorWithStatus:@"用户名已存在"];
//            break;
//        case 313:
//            [SVProgressHUD showErrorWithStatus:@"该用户已经绑定业主，不可重复绑定"];
//            break;
//        case 314:
//            [SVProgressHUD showErrorWithStatus:@"权限不足，无法进行此操作"];
//            break;
//        case 315:
//            [SVProgressHUD showErrorWithStatus:@"该用户没有注册，无法进行此操作"];
//            break;
//        case 320:
//            [SVProgressHUD showErrorWithStatus:@"人员不存在"];
//            break;
//        case 321:
//            [SVProgressHUD showErrorWithStatus:@"业主没有住宅，无法进行此操作"];
//            break;
//        case 322:
//            [SVProgressHUD showErrorWithStatus:@"业主拥有楼宇没有对应管理员"];
//            break;
//        case 323:
//            [SVProgressHUD showErrorWithStatus:@"业主拥有楼宇不能被多个部门负责"];
//            break;
//        case 400:
//            [SVProgressHUD showErrorWithStatus:@"数据不存在"];
//            break;
//        case 401:
//            [SVProgressHUD showErrorWithStatus:@"接口参数不正确"];
//            break;
//        case 500:
//            [SVProgressHUD showErrorWithStatus:@"服务器端未知错误"];
//            break;
//        default:
//            [SVProgressHUD showErrorWithStatus:@"未知的错误"];
//            break;
//    }
//    
//    
//    
//}


+(CGSize)boundingRectWithSize:(NSString*)txt Font:(UIFont*)font Size:(CGSize)size
{
    
    CGSize _size;
    
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_6_1
    
    NSDictionary *attribute = @{NSFontAttributeName: font};
    
    NSStringDrawingOptions options = NSStringDrawingTruncatesLastVisibleLine |
    
    NSStringDrawingUsesLineFragmentOrigin |
    
    NSStringDrawingUsesFontLeading;
    
    _size = [txt boundingRectWithSize:size options: options attributes:attribute context:nil].size;
    
#else
    
    _size = [txt sizeWithFont:font constrainedToSize:size];
    
#endif
    
    return _size;
    
}
+(double)distanceBetweenOrderBy:(double)lat1 :(double)lat2 :(double)lng1 :(double)lng2{
    double dd = M_PI/180;
    double x1=lat1*dd,x2=lat2*dd;
    double y1=lng1*dd,y2=lng2*dd;
    double R = 6371004;
    double distance = (2*R*asin(sqrt(2-2*cos(x1)*cos(x2)*cos(y1-y2) - 2*sin(x1)*sin(x2))/2));
    //km  返回
         return  distance/1000;
    
    //返回 m
//    return   distance;
    
}
+(CGFloat)heightForLabel:(UILabel *)label
                WithText:(NSString *)text
                fontName:(NSString *)fontName
                fontSize:(CGFloat)fontSize
                   width:(CGFloat)width
{
    if (!text)
    {
        return 0;
    }else
    {
        if (!fontName)
        {
            //系统默认的字体
            fontName = @"Helvetica";
        }
        
        //创建字体信息
        UIFont *textFont = [UIFont fontWithName:fontName size:fontSize];
        //字体字典信息
        NSDictionary *fontDict =[NSDictionary dictionaryWithObject:textFont forKey:NSFontAttributeName];
        
        //设置label的属性
        label.frame = CGRectMake(width/2, 0, width, 0);
        label.numberOfLines = 0 ;
        label.lineBreakMode = NSLineBreakByCharWrapping;
        label.backgroundColor = [UIColor clearColor];
        label.font = textFont;
        
        
        CGRect rect = [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT)
                                         options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                      attributes:fontDict
                                         context:nil];
        
        return rect.size.height;
        
    }
    
}

@end
